package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.UserCacheConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.properties.SecurityConfigProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.UserAuth;
import com.zzyl.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Description LoginServiceImpl
 * @Author luohai
 * @Date 2024-10-29
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private SecurityConfigProperties securityConfigProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 用户登录
     * @param loginDto
     */
    @Override
    public UserVo login(LoginDto loginDto) {
        //1.手动激活springsecurity用户登录认证流程
        //手动封装用户名与密码UsernamePasswordAuthenticationToken
        UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword());
        //激活认证流程
        Authentication authenticate = authenticationManager.authenticate(upat);
        //2.判断认证是否成功，不成功抛出异常
        if (!authenticate.isAuthenticated()){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //3.获取认证用户详细信息UserAuth
        UserAuth userAuth = (UserAuth) authenticate.getPrincipal();
        //4.将UserAuth转换为UserVo
        UserVo userVo = BeanUtil.toBean(userAuth, UserVo.class);
        //生成token,将token封装UserVo
        //定义载荷
        Map<String,Object> claims=new HashMap<>();
        claims.put("currentUser", JSONUtil.toJsonStr(userVo));
        //生成token
        String token = JwtUtil.createJWT(
                jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                jwtTokenManagerProperties.getTtl()
                , claims);
        //封装token
        userVo.setUserToken(token);
        //将密码敏感数据处理“*****”
        userVo.setPassword("******");
        //获取用户分配的资源列表
        List<Resource> resourceList=resourceMapper.findListByUserId(userVo.getId());
        List<String> resourcePathList = resourceList.stream().map(i -> i.getRequestPath()).collect(Collectors.toList());
        //获取白名单列表
        List<String> publicAccessUrls = securityConfigProperties.getPublicAccessUrls();
        //合并两个集合
        resourcePathList.addAll(publicAccessUrls);
        //写入缓存
        String key=UserCacheConstant.ACCESS_URLS_CACHE+userVo.getId();
        redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(resourcePathList),30, TimeUnit.MINUTES);
        //返回数据
        return userVo;

    }
}
